package com.bfly.mall.product.controller;

import com.bfly.common.ResponseUtil;
import com.bfly.common.page.Pager;
import com.bfly.common.util.DataConvertUtils;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.context.PagerThreadLocal;
import com.bfly.core.security.ActionModel;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.security.PermissionCheck;
import com.bfly.mall.product.dto.*;
import com.bfly.mall.product.entity.*;
import com.bfly.mall.product.service.IProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/9/21 19:42
 */
@RestController
@RequestMapping(value = "/manage/product")
public class ProductController extends BaseController {

    @Autowired
    private IProductService productService;

    /**
     * 所有产品名称等信息
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/21 19:43
     */
    @GetMapping(value = "/all")
    @PermissionCheck(required = false)
    public void allProductName(HttpServletResponse response) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("is_on_shelf", true);
        List<Product> list = productService.getList(param);
        List<ProductNameDTO> productNames = new ArrayList<>();
        ProductNameDTO nameDTO;
        for (Product product : list) {
            nameDTO = new ProductNameDTO();
            nameDTO.setId(product.getId());
            nameDTO.setName(product.getName());
            productNames.add(nameDTO);
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(productNames));
    }

    /**
     * 产品列表
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/23 16:22
     */
    @GetMapping(value = "/list")
    public void list(HttpServletResponse response, HttpServletRequest request) {
        PagerThreadLocal.set(request);
        String name = request.getParameter("name");
        String onShelf = request.getParameter("shelf");
        String categoryIdStr = request.getParameter("categoryId");
        String tagStr=request.getParameter("tag");

        Map<String, String> unExact = new HashMap<>(1);
        if (StringUtils.isNotBlank(name)) {
            unExact.put("name", name);
        }

        Map<String, Object> exact = new HashMap<>(2);
        if (StringUtils.isNotBlank(onShelf)) {
            exact.put("is_on_shelf", DataConvertUtils.convertToBoolean(onShelf));
        }
        if (StringUtils.isNotBlank(categoryIdStr)) {
            exact.put("category_id", DataConvertUtils.convertToInteger(categoryIdStr));
        }

        if (StringUtils.isNotBlank(tagStr)) {
            exact.put("tag", DataConvertUtils.convertToInteger(tagStr));
        }

        Map<String,Boolean> sortMap=new HashMap<>(2);
        sortMap.put("seq",true);
        sortMap.put("id",false);

        Pager<Product> pager = productService.getPage(exact, unExact, sortMap);
        Pager<ProductListDTO> dtoPager = new Pager<>(pager.getPageNo(), pager.getPageSize(), pager.getTotalCount());

        if (pager.getData() != null) {
            List<ProductListDTO> list = new ArrayList<>();
            for (Product product : pager.getData()) {
                ProductListDTO dto = new ProductListDTO();
                BeanUtils.copyProperties(product, dto);

                dto.setCategoryName(product.getCategory()==null?"":product.getCategory().getName());

                String templateName=product.getFreightTemplate()==null?"":product.getFreightTemplate().getName();
                dto.setFreightTemplateName(templateName);
                dto.setSales(product.getVirtualSales());
                list.add(dto);
            }
            dtoPager.setData(list);
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(dtoPager));
    }

    /**
     * 修改产品上架状态
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/24 10:53
     */
    @GetMapping(value = "/edit/shelf")
    @ActionModel(value = "修改产品上架状态")
    public void editShelf(HttpServletResponse response, @RequestParam("productId") int productId, @RequestParam("shelf") boolean isOnShelf) {
        productService.editShelf(productId, isOnShelf);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 产品详情
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/24 12:11
     */
    @GetMapping(value = "/detail")
    public void detailProduct(HttpServletResponse response, @RequestParam(value = "productId",defaultValue = "0") int productId) {
        Product product = productService.get(productId);
        ProductFormDTO formDTO=new ProductFormDTO();
        BeanUtils.copyProperties(product,formDTO);

        if(product.getTxt()!=null) {
            ProductTxtFormDTO txtFormDTO=new ProductTxtFormDTO();
            BeanUtils.copyProperties(product.getTxt(), txtFormDTO);
            formDTO.setTxt(txtFormDTO);
        }
        if(product.getImgs()!=null){
            List<ProductImgFormDTO> imgs=new ArrayList<>();
            product.getImgs().forEach(productImg -> {
                ProductImgFormDTO imgFormDTO=new ProductImgFormDTO();
                BeanUtils.copyProperties(productImg,imgFormDTO);
                imgs.add(imgFormDTO);
            });
            formDTO.setImgs(imgs);
        }
        if(product.getAttrs()!=null){
            List<ProductAttrFormDTO> attrs=new ArrayList<>();
            product.getAttrs().forEach(productAttr -> {
                ProductAttrFormDTO attrFormDTO=new ProductAttrFormDTO();
                BeanUtils.copyProperties(productAttr,attrFormDTO);
                attrs.add(attrFormDTO);
            });
            formDTO.setAttrs(attrs);
        }
        if(product.getSpeAttrs()!=null){
            List<ProductSpeAttrFormDTO> speAttrs=new ArrayList<>();
            product.getSpeAttrs().forEach(speAttr ->{
                ProductSpeAttrFormDTO speAttrFormDTO=new ProductSpeAttrFormDTO();
                BeanUtils.copyProperties(speAttr,speAttrFormDTO);
                speAttrFormDTO.setData(speAttr.getItems());
                speAttrs.add(speAttrFormDTO);
            });
            formDTO.setSpeAttrs(speAttrs);
        }
        if(product.getSkus()!=null){
            List<ProductSkuFormDTO> skus=new ArrayList<>();
            product.getSkus().forEach(sku ->{
                ProductSkuFormDTO skuFormDTO=new ProductSkuFormDTO();
                BeanUtils.copyProperties(sku,skuFormDTO);
                skus.add(skuFormDTO);
            });
            formDTO.setSkus(skus);
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(formDTO));
    }

    /**
     * 新增产品
     * @author 长沙商脉科技有限公司
     * @date 2020/9/24 12:35
     */
    @PostMapping(value = "/add")
    @ActionModel(value = "新增产品")
    public void addProduct(HttpServletResponse response , @Valid @RequestBody ProductFormDTO formDTO, BindingResult result){
        validData(result);
        productService.save(formDTO);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 编辑产品
     * @author 长沙商脉科技有限公司
     * @date 2020/9/24 12:36
     */
    @PostMapping(value = "/edit")
    @ActionModel(value = "编辑产品")
    public void editProduct(HttpServletResponse response , @Valid @RequestBody ProductFormDTO formDTO, BindingResult result){
        validData(result);
        productService.edit(formDTO);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 删除产品
     * @author 长沙商脉科技有限公司
     * @date 2020/9/24 12:33
     */
    @PostMapping(value = "/delete")
    @ActionModel(value = "删除产品")
    public void delProduct(HttpServletResponse response, @RequestBody Integer...productIds){
        productService.remove(productIds);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 产品排序
     * @author 长沙商脉科技有限公司
     * @date 2020/12/31 9:36
     */
    @GetMapping(value = "/sort")
    @ActionModel(value = "产品排序")
    public void sortProduct(HttpServletResponse response,@RequestParam("productId")int productId,@RequestParam("seq")int seq){
        productService.sortProduct(productId,seq);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }
}